import moment from 'moment';

export const changeTheme = (key: any, value: any) => {
    document.body.style.setProperty('--' + key, value);
};

export const timeAgo = (dateTimeStamp: number) => {
    dateTimeStamp = moment(dateTimeStamp).valueOf();
    let minute = 1000 * 60;
    let hour = minute * 60;
    let day = hour * 24;
    let halfamonth = day * 15;
    let month = day * 30;
    let year = day * 365;
    let now = new Date().getTime();
    let diffValue = now - dateTimeStamp;
    if (diffValue < 0) return;

    let yearC: any = diffValue / year;
    let monthC: any = diffValue / month;
    let weekC: any = diffValue / (7 * day);
    let dayC: any = diffValue / day;
    let hourC: any = diffValue / hour;
    let minC: any = diffValue / minute;
    let result: any = '';
    if (yearC >= 1) {
        result = '' + parseInt(yearC) + '年前';
    } else if (halfamonth === 1) {
        result = '' + '半月前';
    } else if (monthC >= 1) {
        result = '' + parseInt(monthC) + '月前';
    } else if (weekC >= 1) {
        result = '' + parseInt(weekC) + '周前';
    } else if (dayC >= 1) {
        result = '' + parseInt(dayC) + '天前';
    } else if (hourC >= 1) {
        result = '' + parseInt(hourC) + '小时前';
    } else if (minC >= 1) {
        result = '' + parseInt(minC) + '分钟前';
    } else {
        result = '刚刚';
    }
    return result;
};

export const debounce = (idle: number, action: any) => {
    let last: NodeJS.Timeout, args: any;
    return function () {
        args = arguments;
        clearTimeout(last);
        last = setTimeout(() => {
            action(args)
        }, idle);
    };
};
